package com.example.planetexploder.model.folder;

import android.content.Context;
import android.util.Log;

import com.example.planetexploder.constants.LogConst;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import static com.example.planetexploder.constants.FolderConst.TEXT_FOLDER_NAME;

/**
 * 文本文件操作类
 * @author 蒋子涵
 * 2019.10.15
 */
public class TextFile {

    private File root;
    private Context context;

    public TextFile(Context context, File root){
        this.context = context;
        this.root = root;
    }
    /**
     * 保存文本文件
     * @param bookId  摘抄集id
     * @param text    文本文件
     */
    public void save_Text(String bookId, String textId, String text) throws Exception {
        Log.d(LogConst.MTAG, "save_Text()");
        File file = new File(root,bookId+"/"+TEXT_FOLDER_NAME + "/"+textId+".txt");
        FileOutputStream output = new FileOutputStream(file);
        output.write(text.getBytes());  //将String字符串以字节流的形式写入到输出流中
        output.close();         //关闭输出流
    }

    /**
     * 删除文本文件
     * @param bookId  摘抄集id
     */
    public void delete_Text(String bookId, String textId) {
        Log.d(LogConst.MTAG, "delete_Text()");
        File file = new File(root,bookId+"/"+TEXT_FOLDER_NAME + "/"+textId+".txt");
        if(file.exists())
            file.delete();
    }

    /**
     * 获取文本文件
     * @param bookId  摘抄集id
     * @return        文本文件
     */
    public String get_Text(String bookId, String textId) throws Exception {
        Log.d(LogConst.MTAG, "get_Text()");
        File file = new File(root,bookId+"/"+TEXT_FOLDER_NAME + "/"+textId+".txt");
        FileInputStream input = new FileInputStream(file);

        byte[] temp = new byte[1024];
        StringBuilder sb = new StringBuilder("");
        int len = 0;
        //读取文件内容:
        while ((len = input.read(temp)) > 0) {
            sb.append(new String(temp, 0, len));
        }
        //关闭输入流
        input.close();
        return sb.toString();
    }

}
